<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';

header('Content-Type: application/json');

// 检查管理员权限
if (!isset($_SESSION['user_id']) || $_SESSION['username'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => '无权限']);
    exit;
}

try {
    // 获取当前价格和轮次
    $current_price = getCurrentPrice();
    $current_round = getCurrentRound();
    
    // 获取当前轮次的价格历史
    $stmt = $pdo->prepare("
        SELECT price, timestamp 
        FROM price_history 
        WHERE round_id = ? 
        ORDER BY timestamp DESC 
        LIMIT 50
    ");
    $stmt->execute([$current_round['id']]);
    $price_history = array_reverse($stmt->fetchAll());
    
    // 获取交易数据，按时间戳分组
    $stmt = $pdo->prepare("
        SELECT 
            DATE_FORMAT(transaction_time, '%Y-%m-%d %H:%i:00') as time_group,
            SUM(quantity) as trade_quantity,
            SUM(CASE WHEN type = 'buy' THEN quantity ELSE 0 END) as buy_quantity,
            SUM(CASE WHEN type = 'sell' THEN quantity ELSE 0 END) as sell_quantity,
            SUM(amount) as trade_volume
        FROM transactions
        WHERE round_id = ?
        GROUP BY time_group
        ORDER BY time_group
    ");
    $stmt->execute([$current_round['id']]);
    $trade_data = $stmt->fetchAll();
    
    // 获取价格交易统计
    $stmt = $pdo->prepare("
        SELECT 
            ROUND(price, 2) AS price_point,
            SUM(CASE WHEN type = 'buy' THEN quantity ELSE 0 END) AS buy_quantity,
            SUM(CASE WHEN type = 'sell' THEN quantity ELSE 0 END) AS sell_quantity,
            COUNT(CASE WHEN type = 'buy' THEN 1 ELSE NULL END) AS buy_count,
            COUNT(CASE WHEN type = 'sell' THEN 1 ELSE NULL END) AS sell_count
        FROM transactions
        WHERE round_id = ?
        GROUP BY ROUND(price, 2)
        ORDER BY price_point DESC
    ");
    $stmt->execute([$current_round['id']]);
    $price_stats = $stmt->fetchAll();
    
    // 获取当前价格趋势设置
    $current_trend = $_SESSION['admin_price_trend'] ?? 'random';
    $current_strength = $_SESSION['admin_price_strength'] ?? 5;
    
    echo json_encode([
        'success' => true,
        'current_price' => $current_price,
        'round_info' => [
            'round_number' => $current_round['round_number'],
            'status' => $current_round['status'],
            'status_text' => getRoundStatusText($current_round['status']),
            'end_time' => $current_round['end_time']
        ],
        'price_history' => $price_history,
        'trade_data' => $trade_data,
        'price_stats' => $price_stats,
        'trend' => $current_trend,
        'strength' => $current_strength
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => '获取价格统计数据失败: ' . $e->getMessage()
    ]);
}
?>
